#include "config.h"

#define TIMER_NUM       (3)

static volatile uint32_t g_systick_time = 0;
static uint32_t delay_timer[TIMER_NUM] = {0};

/* 滴答定时器中断处理函数 */
void SysTick_irq_Handle(void)
{
    int i = 0;
    g_systick_time++;
    if(g_systick_time == 0xFFFFFFFF) {
        g_systick_time = 0;
    }

    for (i = 0; i < TIMER_NUM; i++) {
        if(delay_timer[i] > 0) {
            delay_timer[i]--;
        }
    }
}
/**
 * @brief 系统滴答定时器初始化
 * @param 无
 * @return 无
 */
void systick_init(void)
{
	CORET_DeInit();
	SYSCON_General_CMD(ENABLE, ENDIS_SYSTICK);
	CK801->CORET_RVR = 2999; // period 1ms.
	//CORETCLK=sysclock/8=24M/8=3Mhz 
	//e.g:1ms=(CORET_RVR+1)*(8/24M);CORET_RVR=3000-1=2999
	CORET_reload();         // Coret CVR 清除
	CORET_CLKSOURCE_EX();   //使用时钟源为 sysclk/8
	CORET_TICKINT_Enable(); //使能计数器清零中断
	CORET_start();          //Coret 计时开始
	CORET_Int_Enable();     //使能计数器清零中断向量
    CORET_WakeUp_Disable();
    g_systick_time = 0;
}

/**
 * @brief 释放滴答定时器
 * @param 无
 * @return 无
 */
void systick_deinit(void)
{
	CORET_DeInit();
	SYSCON_General_CMD(ENABLE, ENDIS_SYSTICK);
	CORET_Int_Disable();
    CORET_WakeUp_Disable();
    g_systick_time = 0;
}

/**
 * @brief 系统滴答延时
 * @param delay_ms 
 * @return 无
 */
void systick_delay_ms(uint32_t delay_ms)
{
    CORET_Int_Disable();
    delay_timer[0] = delay_ms;
    CORET_Int_Enable();
    while(delay_timer[0]) {
        SYSCON_IWDCNT_Reload();
    };
}

/**
 * @brief 获取当前系统运行时间，单位ms
 * @param 无
 * @return 无
 */
uint32_t systick_get_current_stamp(void)
{
    uint32_t stmp = 0;
    CORET_Int_Disable();
    stmp = g_systick_time;
    CORET_Int_Enable();
    return stmp;
}


